package cn.dcw.pethome.basic.controller;

import cn.dcw.pethome.basic.util.AjaxResult;
import cn.dcw.pethome.basic.util.FastDfsUtil;
import cn.dcw.pethome.org.dto.LogDto;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.MessageDigest;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/fastDfs")
public class fastDfsController {
    /**
     * 上传文件
     * required = true  必须要上传文件，不然就报错
     * value = "file"   固定写法  elementUi封装好的
     */
    @PostMapping
    public AjaxResult upload( @RequestParam(required = true,value = "file") MultipartFile file) {
        try {
            //获取原始文件名称
            String originalFilename = file.getOriginalFilename();
            //获取后缀  .gif
            String endName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用工具类，上传文件
            String path = FastDfsUtil.upload(file.getBytes(), endName);//返回上传的路径，发送到前端页面
            return new AjaxResult(true, "上传成功", path);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "上传失败");
        }
    }

    /*
    删除上传文件
     */
    @PostMapping("/del")
    public AjaxResult delUpload(@RequestBody LogDto logDto){
        System.out.println(logDto);
        try {
            //   path   /group1/M00/00/F6/rBE3kWEaQumAQ0FyAADdj5ZcvfY344.png
            //根据上面路径找到文件保存的地址，并删除
            String substring = logDto.getFilePath().substring(1);//去掉第一个斜杠   group1/M00/00/F6/rBE3kWEaQumAQ0FyAADdj5ZcvfY344.png
            String groupName = substring.substring(0, substring.indexOf("/"));//group1
            String fileName = substring.substring(substring.indexOf("/") + 1);
            //调用方法，删除上传文件
            FastDfsUtil.delete(groupName, fileName);
            return new AjaxResult(true,"*删除成功*");
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"系统异常，请稍后***");
        }
    }
}
